package com.sjmsks.Jpanels.work.shape;

import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// TODO 原型模式的实现
public class ShapeFactory {

	private Map<String, Shape> shapeMap = new HashMap<>();

	private static ShapeFactory shapeFactory;

	// 隐藏构造方法
	private ShapeFactory() {
	}

	// TODO 单例模式的实现
	public static synchronized ShapeFactory getInstance() {

		// 如果对象为空则创建
		if (shapeFactory == null) {
			shapeFactory = new ShapeFactory();
		}
		return shapeFactory;
	}


	static List<String> supportShape = List.of(new String[]{"circle", "triangle", "rectangle"});

	public AbstractShape getShape(String shapeType, Color color, Stroke stroke) throws UnSupportShapeException, CloneNotSupportedException {

		AbstractShape shape;

		if (!supportShape.contains(shapeType)) {
			throw new UnSupportShapeException();
		}

		if (!shapeMap.containsKey(shapeType)) {
			shape = switch (shapeType) {
				case "circle" -> new Circle();
				case "triangle" -> new Triangle();
				case "rectangle" -> new Rectangle();
				default -> throw new UnSupportShapeException();
			};
			shapeMap.put(shapeType, shape);
		} else {
			shape = (AbstractShape) shapeMap.get(shapeType);
		}
		AbstractShape clone = (AbstractShape) shape.clone();
		clone.setColor(color);
		clone.setStroke(stroke);
		return clone;
	}
}
